package com.tcoding.client.utils;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.UUID;

public class ImageUtil {

 public static void main(String[] args) throws IOException {
        long timeStart = System.currentTimeMillis();
        // 创建本地文件
        File file = new File("E:\\666.jpg");
        // 生成临时文件
        File zipFile = File.createTempFile(UUID.randomUUID().toString(), file.getName());
        // 压缩文件
        compressUnderSize(file, 100 * 1024, zipFile);
        // 默认地址:C:\Users\Administrator\AppData\Local\Temp
        System.out.println(zipFile.getAbsolutePath());
        // 删除临时文件
        /// zipFile.delete();
        long timeEnd = System.currentTimeMillis();
        System.out.println("耗时：" + (timeEnd - timeStart));
    }

	/**
     * 将图片压缩到指定大小以内
     *
     * @param imageFile 源图片数据
     * @param maxSize 目的图片大小
     * @return
     * @author CY
     * @date 2020年11月18日
     */
    public static void compressUnderSize(File imageFile, long maxSize, File zipFile) throws IOException {
        byte[] data = getByteByPic(imageFile);
        byte[] imgData = Arrays.copyOf(data, data.length);
        do {
            try {
                imgData = compress(imgData, 0.9);
            } catch (IOException e) {
                throw new IllegalStateException("压缩图片过程中出错,请及时联系管理员!", e);
            }
        } while (imgData.length > maxSize);
        byteToImage(imgData, zipFile);
    }

    /**
     * 获取图片文件字节
     *
     * @param imageFile
     * @return
     * @throws IOException
     * @author CY
     * @date 2020年11月18日
     */
    public static byte[] getByteByPic(File imageFile) throws IOException {
        InputStream inStream = new FileInputStream(imageFile);
        BufferedInputStream bis = new BufferedInputStream(inStream);
        BufferedImage bm = ImageIO.read(bis);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String imageUrl = imageFile.getAbsolutePath();
        String type = imageUrl.substring(imageUrl.length() - 3);
        ImageIO.write(bm, type, bos);
        bos.flush();
        byte[] data = bos.toByteArray();
        return data;
    }

    /**
     * 按照宽高比例压缩
     *
     * @param srcImgData 待压缩图片输入流
     * @param scale 压缩刻度
     * @return
     * @throws IOException
     * @author CY
     * @date 2020年11月18日
     */
    public static byte[] compress(byte[] srcImgData, double scale) throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        int width = (int) (bi.getWidth() * scale); // 源图宽度
        int height = (int) (bi.getHeight() * scale); // 源图高度
        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null); // 绘制处理后的图
        g.dispose();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bOut);
        return bOut.toByteArray();
    }

    /**
     * byte数组转图片
     *
     * @param data
     * @param zipFile
     * @author CY
     * @date 2020年11月18日
     */
    public static void byteToImage(byte[] data, File zipFile) {
        if (data.length < 3){
            return;
        }
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(zipFile);
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static String getSuffix(File file){

        if(file==null){
            return null;
        }
        String name = file.getName();
        String[] split = StringUtils.split(name, ".");
        return "."+split[split.length-1];
    }


    /**
     *  对字节数组字符串进行Base64解码并生成图片
     * @param imgStr
     * @param file
     * @return
     */
    public static boolean GenerateImage(String imgStr, File file) {
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
